// Package admin
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package admin

import (
	"context"
	"database/sql"
	"fmt"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/global"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/dict"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/library/hgorm/hook"
	"hotgo/internal/model"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/model/input/apiin"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/tree"
	"hotgo/utility/validate"
	"sync"

	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/database/gredis"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/grand"
)

// SuperAdmin 超级管理员用户
type SuperAdmin struct {
	sync.RWMutex
	RoleId    int64              // 超管角色ID
	MemberIds map[int64]struct{} // 超管用户ID
}

type sAdminMember struct {
	superAdmin *SuperAdmin
}

func NewAdminMember() *sAdminMember {
	return &sAdminMember{
		superAdmin: new(SuperAdmin),
	}
}

func init() {
	service.RegisterAdminMember(NewAdminMember())
	dict.RegisterFunc("memberOption", "用户选项", service.AdminMember().Option)
}

func (s *sAdminMember) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.AdminMember.Ctx(ctx), option...)
}

// AddBalance 增加余额
func (s *sAdminMember) AddBalance(ctx context.Context, in *adminin.MemberAddBalanceInp) (err error) {
	var (
		mb       *entity.AdminMember
		memberId = contexts.GetUserId(ctx)
	)

	if err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		// 更新我的余额
		_, err = service.AdminCreditsLog().SaveBalance(ctx, &adminin.CreditsLogSaveBalanceInp{
			MemberId:    memberId,
			AppId:       in.AppId,
			AddonsName:  in.AddonsName,
			CreditGroup: in.SelfCreditGroup,
			Num:         in.SelfNum,
			Remark:      fmt.Sprintf("为后台用户:%v 操作%v", mb.Id, in.Remark),
		})
		if err != nil {
			return
		}

		// 更新对方余额
		_, err = service.AdminCreditsLog().SaveBalance(ctx, &adminin.CreditsLogSaveBalanceInp{
			MemberId:    mb.Id,
			AppId:       in.AppId,
			AddonsName:  in.AddonsName,
			CreditGroup: in.OtherCreditGroup,
			Num:         in.OtherNum,
			Remark:      fmt.Sprintf("后台用户:%v 为你操作%v", memberId, in.Remark),
		})
		return
	})
}

// AddIntegral 增加积分
func (s *sAdminMember) AddIntegral(ctx context.Context, in *adminin.MemberAddIntegralInp) (err error) {
	var (
		mb       *entity.AdminMember
		memberId = contexts.GetUserId(ctx)
	)

	if err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		// 更新我的余额
		_, err = service.AdminCreditsLog().SaveIntegral(ctx, &adminin.CreditsLogSaveIntegralInp{
			MemberId:    memberId,
			AppId:       in.AppId,
			AddonsName:  in.AddonsName,
			CreditGroup: in.SelfCreditGroup,
			Num:         in.SelfNum,
			Remark:      fmt.Sprintf("为用户:%v 操作%v", mb.Id, in.Remark),
		})
		if err != nil {
			return
		}

		// 更新对方余额
		_, err = service.AdminCreditsLog().SaveIntegral(ctx, &adminin.CreditsLogSaveIntegralInp{
			MemberId:    mb.Id,
			AppId:       in.AppId,
			AddonsName:  in.AddonsName,
			CreditGroup: in.OtherCreditGroup,
			Num:         in.OtherNum,
			Remark:      fmt.Sprintf("后户:%v 为你操作%v", memberId, in.Remark),
		})
		return
	})
}

// UpdateCash 修改提现信息
func (s *sAdminMember) UpdateCash(ctx context.Context, in *adminin.MemberUpdateCashInp) (err error) {
	memberId := contexts.Get(ctx).User.Id
	if memberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	var mb entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if gmd5.MustEncryptString(in.Password+mb.Salt) != mb.PasswordHash {
		err = gerror.New("登录密码不正确")
		return
	}

	_, err = dao.AdminMember.Ctx(ctx).WherePri(memberId).
		Data(g.Map{
			dao.AdminMember.Columns().Cash: adminin.MemberCash{
				Name:      in.Name,
				Account:   in.Account,
				PayeeCode: in.PayeeCode,
			},
		}).
		Update()

	if err != nil {
		err = gerror.New("修改提现信息失败！")
		return
	}
	return
}

// UpdateEmail 换绑邮箱
func (s *sAdminMember) UpdateEmail(ctx context.Context, in *adminin.MemberUpdateEmailInp) (err error) {
	memberId := contexts.Get(ctx).User.Id
	if memberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	var mb *entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	if mb.Email == in.Email {
		err = gerror.New("新旧邮箱不能一样")
		return
	}

	if !validate.IsEmail(in.Email) {
		err = gerror.New("邮箱地址不正确")
		return
	}

	// 存在原绑定号码，需要进行验证
	if mb.Email != "" {
		err = service.SysEmsLog().VerifyCode(ctx, &sysin.VerifyEmsCodeInp{
			Event: consts.EmsTemplateBind,
			Email: mb.Email,
			Code:  in.Code,
		})
		if err != nil {
			return
		}
	}

	update := g.Map{
		dao.AdminMember.Columns().Email: in.Email,
	}

	if _, err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Data(update).Update(); err != nil {
		err = gerror.Wrap(err, "换绑邮箱失败，请稍后重试！")
		return
	}
	return
}

// UpdateMobile 换绑手机号
func (s *sAdminMember) UpdateMobile(ctx context.Context, in *adminin.MemberUpdateMobileInp) (err error) {
	memberId := contexts.Get(ctx).User.Id
	if memberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	var mb *entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	if mb.Mobile == in.Mobile {
		err = gerror.New("新旧手机号不能一样")
		return
	}

	if !validate.IsMobile(in.Mobile) {
		err = gerror.New("手机号码不正确")
		return
	}

	// 存在原绑定号码，需要进行验证
	if mb.Mobile != "" {
		err = service.SysSmsLog().VerifyCode(ctx, &sysin.VerifyCodeInp{
			Event:  consts.SmsTemplateBind,
			Mobile: mb.Mobile,
			Code:   in.Code,
		})
		if err != nil {
			return
		}
	}

	update := g.Map{
		dao.AdminMember.Columns().Mobile: in.Mobile,
	}

	if _, err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Data(update).Update(); err != nil {
		err = gerror.Wrap(err, "换绑手机号失败，请稍后重试！")
		return
	}
	return
}

// UpdateProfile 更新用户资料
func (s *sAdminMember) UpdateProfile(ctx context.Context, in *adminin.MemberUpdateProfileInp) (err error) {
	memberId := contexts.Get(ctx).User.Id
	if memberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	var mb *entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	cols := dao.AdminMember.Columns()
	update := g.Map{
		cols.Avatar:   in.Avatar,
		cols.RealName: in.RealName,
		cols.Qq:       in.Qq,
		cols.Birthday: in.Birthday,
		cols.Sex:      in.Sex,
		cols.CityId:   in.CityId,
		cols.Address:  in.Address,
	}

	if _, err = dao.AdminMember.Ctx(ctx).WherePri(memberId).Data(update).Update(); err != nil {
		err = gerror.Wrap(err, "更新资料失败，请稍后重试！")
		return
	}
	return
}

// UpdatePwd 修改登录密码
func (s *sAdminMember) UpdatePwd(ctx context.Context, in *adminin.MemberUpdatePwdInp) (err error) {
	var mb entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(in.Id).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if gmd5.MustEncryptString(in.OldPassword+mb.Salt) != mb.PasswordHash {
		err = gerror.New("原密码不正确")
		return
	}

	update := g.Map{
		dao.AdminMember.Columns().PasswordHash: gmd5.MustEncryptString(in.NewPassword + mb.Salt),
	}

	if _, err = dao.AdminMember.Ctx(ctx).WherePri(in.Id).Data(update).Update(); err != nil {
		err = gerror.Wrap(err, "更新登录密码失败，请稍后重试！")
		return
	}
	return
}

// ResetPwd 重置密码
func (s *sAdminMember) ResetPwd(ctx context.Context, in *adminin.MemberResetPwdInp) (err error) {
	var (
		mb       *entity.AdminMember
		memberId = contexts.GetUserId(ctx)
	)

	if err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if mb == nil {
		err = gerror.New("用户信息不存在")
		return
	}

	update := g.Map{
		dao.AdminMember.Columns().PasswordHash: gmd5.MustEncryptString(in.Password + mb.Salt),
	}

	if _, err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Data(update).Update(); err != nil {
		err = gerror.Wrap(err, "用户密码重置失败，请稍后重试！")
		return
	}
	return
}

// VerifyUnique 验证管理员唯一属性
func (s *sAdminMember) VerifyUnique(ctx context.Context, in *adminin.VerifyUniqueInp) (err error) {
	if in.Where == nil {
		return
	}

	cols := dao.AdminMember.Columns()
	msgMap := g.MapStrStr{
		cols.Username:   "用户名已存在，请换一个",
		cols.Email:      "邮箱已存在，请换一个",
		cols.Mobile:     "手机号已存在，请换一个",
		cols.InviteCode: "邀请码已存在，请换一个",
	}

	for k, v := range in.Where {
		if v == "" {
			continue
		}
		message, ok := msgMap[k]
		if !ok {
			err = gerror.Newf("字段 [ %v ] 未配置唯一属性验证", k)
			return
		}
		if err = hgorm.IsUnique(ctx, &dao.AdminMember, g.Map{k: v}, message, in.Id, in.RoleId); err != nil {
			return
		}
	}
	return
}

// Delete 删除用户
func (s *sAdminMember) Delete(ctx context.Context, in *adminin.MemberDeleteInp) (err error) {
	memberId := contexts.GetUserId(ctx)
	if memberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	var list []*entity.AdminMember
	if err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Scan(&list); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if len(list) == 0 {
		err = gerror.New("需要删除的用户不存在或已删除！")
		return
	}

	isStore := false
	for _, v := range list {
		if s.VerifySuperId(ctx, v.Id) {
			err = gerror.New("超管账号禁止删除！")
			return
		}
		count, err := dao.AdminMember.Ctx(ctx).Where("pid", v.Id).Count()
		if err != nil {
			err = gerror.Wrap(err, "删除用户检查失败，请稍后重试！")
			return err
		}
		if count > 0 {
			err = gerror.Newf("用户[%v]存在下级，请先删除TA的下级用户！", v.Id)
			return err
		}
		if v.RoleId == consts.RoleStore && v.StoreType == 1 {
			isStore = true
		}
	}

	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		if isStore {
			// 帐号删除管理门店
			_, err = dao.StoreMember.Ctx(ctx).
				Where(dao.StoreMember.Columns().MemberId, in.Id).Delete()
			if err != nil {
				return gerror.Wrap(err, "删除用户失败，请稍后重试！")
			}

			// 删除门店关联的商户
			_, err = dao.Store.Ctx(ctx).
				Where(dao.Store.Columns().BusinessId, in.Id).Data(g.Map{
				dao.Store.Columns().BusinessId: nil,
			}).Update()
			if err != nil {
				return gerror.Wrap(err, "删除用户失败，请稍后重试！")
			}
		}

		if _, err = s.FilterAuthModel(ctx, memberId).WherePri(in.Id).Delete(); err != nil {
			err = gerror.Wrap(err, "删除用户失败，请稍后重试！")
			return
		}

		if _, err = dao.AdminMemberPost.Ctx(ctx).Where("member_id", in.Id).Delete(); err != nil {
			err = gerror.Wrap(err, "删除用户岗位失败，请稍后重试！")
		}

		// 这里如果需要，可以加入更多删除用户的相关处理
		// ...
		return
	})
}

// Edit 修改/新增用户
func (s *sAdminMember) Edit(ctx context.Context, in *adminin.MemberEditInp) (err error) {
	opMemberId := contexts.GetUserId(ctx)
	if opMemberId <= 0 {
		err = gerror.New("获取用户信息失败！")
		return
	}

	if consts.IsManager(in.RoleId) &&
		in.Username == "" {
		err = gerror.New("帐号不能为空")
		return
	}

	cols := dao.AdminMember.Columns()
	err = s.VerifyUnique(ctx, &adminin.VerifyUniqueInp{
		Id:     in.Id,
		RoleId: in.RoleId,
		Where: g.Map{
			cols.Username: in.Username,
			cols.Mobile:   in.Mobile,
			cols.Email:    in.Email,
		},
	})
	if err != nil {
		if in.StoreType == 1 && in.RoleId == consts.RoleStore && err.Error() == "手机号已存在，请换一个" {
			res, err2 := service.AdminMember().GetByMobile(ctx, in.Mobile, []int{consts.RoleStore})
			if err2 != nil {
				err = gerror.Wrap(err2, "获取用户信息失败，请稍后重试！")
				return
			}
			in.Id = res.Id
		} else {
			return
		}
	}

	// 验证角色ID
	if err = service.AdminRole().VerifyRoleId(ctx, in.RoleId); err != nil {
		return
	}

	// 验证部门ID
	if err = service.AdminDept().VerifyDeptId(ctx, in.DeptId); err != nil {
		return
	}

	config, err := service.SysConfig().GetLogin(ctx)
	if err != nil {
		return
	}

	needLoadSuperAdmin := false
	defer func() {
		if needLoadSuperAdmin {
			// 本地先更新
			s.LoadSuperAdmin(ctx)
			// 推送消息让所有集群再同步一次
			global.PublishClusterSync(ctx, consts.ClusterSyncSysSuperAdmin, nil)
		}
	}()

	// 修改
	if in.Id > 0 {
		if s.VerifySuperId(ctx, in.Id) {
			err = gerror.New("超管账号禁止编辑！")
			return
		}

		mod := s.FilterAuthModel(ctx, opMemberId)

		if in.Password != "" {
			// 修改密码，需要获取到密码盐
			salt, err := s.FilterAuthModel(ctx, opMemberId).Fields(cols.Salt).WherePri(in.Id).Value()
			if err != nil {
				err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
				return err
			}
			if salt.IsEmpty() {
				err = gerror.New("该用户没有设置密码盐，请联系管理员！")
				return err
			}
			in.PasswordHash = gmd5.MustEncryptString(in.Password + salt.String())
		} else {
			mod = mod.FieldsEx(cols.PasswordHash)
		}

		return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
			if _, err = mod.WherePri(in.Id).Data(in).OmitEmpty().Update(); err != nil {
				err = gerror.Wrap(err, "修改用户信息失败，请稍后重试！")
				return
			}

			// 更新岗位
			if err = service.AdminMemberPost().UpdatePostIds(ctx, in.Id, in.PostIds); err != nil {
				err = gerror.Wrap(err, "更新用户岗位失败，请稍后重试！")
			}

			needLoadSuperAdmin = in.RoleId == s.superAdmin.RoleId
			return
		})
	}

	// 新增用户时的额外属性
	var data adminin.MemberAddInp
	data.MemberEditInp = in
	data.Salt = grand.S(6)
	data.InviteCode = grand.S(12)
	data.PasswordHash = gmd5.MustEncryptString(data.Password + data.Salt)

	// 关系树
	data.Pid = opMemberId
	data.Level, data.Tree, err = s.GenTree(ctx, opMemberId)
	if err != nil {
		return
	}

	// 默认头像
	if data.Avatar == "" {
		data.Avatar = config.Avatar
	}

	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		id, err := dao.AdminMember.Ctx(ctx).Data(data).OmitEmptyData().InsertAndGetId()
		if err != nil {
			err = gerror.Wrap(err, "新增用户失败，请稍后重试！")
			return
		}

		// 更新岗位
		if err = service.AdminMemberPost().UpdatePostIds(ctx, id, in.PostIds); err != nil {
			err = gerror.Wrap(err, "新增用户岗位失败，请稍后重试！")
		}

		needLoadSuperAdmin = in.RoleId == s.superAdmin.RoleId
		return
	})
}

// 修改用户信息
func (s *sAdminMember) UpdateInfo(ctx context.Context, in *adminin.MemberUpdateInfoInp) (err error) {
	if in.Nickname == "" && in.Mobile == "" && in.Avatar == "" &&
		in.Label == nil && in.ExpireTime == nil && in.ExchangeCount == 0 &&
		in.MemberStartTime == nil && in.RoleId == 0 && in.RealName == "" &&
		in.IdCard == "" {
		return
	}

	data := g.Map{}

	if in.Avatar != "" {
		data[dao.AdminMember.Columns().Avatar] = in.Avatar
	}
	if in.Nickname != "" {
		data[dao.AdminMember.Columns().Nickname] = in.Nickname
	}
	if in.Mobile != "" {
		data[dao.AdminMember.Columns().Mobile] = in.Mobile
	}
	if in.Label != nil {
		data[dao.AdminMember.Columns().Label] = in.Label
	}
	if in.MemberType > 0 {
		data[dao.AdminMember.Columns().MemberType] = in.MemberType
	}
	if in.MemberStatus > 0 {
		data[dao.AdminMember.Columns().MemberStatus] = in.MemberStatus
	}
	if in.ExpireTime != nil {
		data[dao.AdminMember.Columns().ExpireTime] = in.ExpireTime
	}
	if in.ExchangeCount > 0 {
		data[dao.AdminMember.Columns().ExchangeCount] = in.ExchangeCount
	}
	if in.MemberStartTime != nil {
		data[dao.AdminMember.Columns().MemberStartTime] = in.MemberStartTime
	}
	if in.RoleId > 0 {
		data[dao.AdminMember.Columns().RoleId] = in.RoleId
	}
	if in.RealName != "" {
		data[dao.AdminMember.Columns().RealName] = in.RealName
	}
	if in.IdCard != "" {
		data[dao.AdminMember.Columns().IdCard] = in.IdCard
	}

	// 根据ID修改字段
	if _, err = s.Model(ctx).Where(dao.AdminMember.Columns().Id, in.ID).Data(data).Update(); err != nil {
		err = gerror.Wrap(err, "修改用户信息失败，请稍后重试！")
	}
	return
}

// 会员用户重置为普通用户
func (s *sAdminMember) ResetMember(ctx context.Context, id int64) (err error) {
	if _, err = s.Model(ctx).WherePri(id).Data(g.Map{
		dao.AdminMember.Columns().MemberStatus:    consts.AdminMemberMemberStatusUser, // 非会员
		dao.AdminMember.Columns().MemberType:      consts.AdminMemberMemberTypeNone,   // 无会员
		dao.AdminMember.Columns().MemberStartTime: nil,                                // 清空会员开始时间
		dao.AdminMember.Columns().ExchangeCount:   0,                                  // 重置兑换次数
		dao.AdminMember.Columns().ExpireTime:      nil,                                // 清空到期时间
	}).Update(); err != nil {
		err = gerror.Wrap(err, "会员用户重置为普通用户失败，请稍后重试！")
		return
	}
	return
}

// View 获取用户信息
func (s *sAdminMember) View(ctx context.Context, in *adminin.MemberViewInp) (res *adminin.MemberViewModel, err error) {
	if err = s.FilterAuthModel(ctx, contexts.GetUserId(ctx)).Hook(hook.MemberInfo).WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
	}
	return
}

// List 获取用户列表
func (s *sAdminMember) List(ctx context.Context, in *adminin.MemberListInp) (list []*adminin.MemberListModel, totalCount int, err error) {
	//mod := s.FilterAuthModel(ctx, contexts.GetUserId(ctx))
	mod := s.Model(ctx)
	cols := dao.AdminMember.Columns()

	if in.RealName != "" {
		mod = mod.WhereLike(cols.RealName, "%"+in.RealName+"%")
	}

	if in.Username != "" {
		mod = mod.WhereLike(cols.Username, "%"+in.Username+"%")
	}

	if in.Mobile > 0 {
		mod = mod.Where(cols.Mobile, in.Mobile)
	}

	if in.Status > 0 {
		mod = mod.Where(cols.Status, in.Status)
	}

	if in.DeptId > 0 {
		mod = mod.Where(cols.DeptId, in.DeptId)
	}

	if in.RoleId > 0 {
		mod = mod.Where(cols.RoleId, in.RoleId)
	}

	if len(in.RoleIds) > 0 {
		mod = mod.WhereIn(cols.RoleId, in.RoleIds)
	}

	if in.Id > 0 {
		mod = mod.Where(cols.Id, in.Id)
	}

	if in.Pid > 0 {
		mod = mod.Where(cols.Pid, in.Pid)
	}

	if in.StoreType > 0 {
		mod = mod.Where(cols.StoreType, in.StoreType)
	}

	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(cols.CreatedAt, gtime.New(in.CreatedAt[0]), gtime.New(in.CreatedAt[1]))
	}

	if err = mod.
		//Hook(hook.MemberInfo).
		Page(in.Page, in.PerPage).OrderDesc(cols.Id).ScanAndCount(&list, &totalCount, true); err != nil {
		err = gerror.Wrap(err, "获取用户列表失败！")
		return
	}

	for _, v := range list {
		columns, err := dao.AdminMemberPost.Ctx(ctx).Fields(dao.AdminMemberPost.Columns().PostId).Where(dao.AdminMemberPost.Columns().MemberId, v.Id).Array()
		if err != nil {
			err = gerror.Wrap(err, "获取用户岗位数据失败！")
			return nil, 0, err
		}
		v.PostIds = g.NewVar(columns).Int64s()
	}
	return
}

// Status 更新状态
func (s *sAdminMember) Status(ctx context.Context, in *adminin.MemberStatusInp) (err error) {
	if s.VerifySuperId(ctx, in.Id) {
		err = gerror.New("超管账号不能更改状态")
		return
	}

	if _, err = s.FilterAuthModel(ctx, contexts.GetUserId(ctx)).WherePri(in.Id).Data(dao.AdminMember.Columns().Status, in.Status).Update(); err != nil {
		err = gerror.Wrap(err, "更新用户状态失败，请稍后重试！")
	}
	return
}

// GenTree 生成关系树
func (s *sAdminMember) GenTree(ctx context.Context, pid int64) (level int, newTree string, err error) {
	var pmb *entity.AdminMember
	if err = dao.AdminMember.Ctx(ctx).WherePri(pid).Scan(&pmb); err != nil {
		return
	}

	if pmb == nil {
		err = gerror.New("上级信息不存在")
		return
	}

	level = pmb.Level + 1
	newTree = tree.GenLabel(pmb.Tree, pmb.Id)
	return
}

// LoginMemberInfo 获取登录用户信息
func (s *sAdminMember) LoginMemberInfo(ctx context.Context) (res *adminin.LoginMemberInfoModel, err error) {

	res = new(adminin.LoginMemberInfoModel)
	res.Store = new(entity.Store)

	var memberId = contexts.GetUserId(ctx)
	if memberId <= 0 {
		err = gerror.NewCode(gcode.CodeNotAuthorized, "用户身份异常，请重新登录！")
		return
	}

	if err = dao.AdminMember.Ctx(ctx).Hook(hook.MemberInfo).WherePri(memberId).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
		return
	}

	if res == nil {
		err = gerror.New("用户不存在！")
		return
	}

	res.Distribution = &adminin.DistributionCenterModel{}

	// 细粒度权限
	permissions, err := service.AdminMenu().LoginPermissions(ctx, memberId)
	if err != nil {
		return
	}
	res.Permissions = permissions

	// 登录统计
	stat, err := s.MemberLoginStat(ctx, &adminin.MemberLoginStatInp{MemberId: memberId})
	if err != nil {
		return
	}

	// 新人积分设置 TODO 临时设置新人不弹框
	//if garray.NewStrArrayFrom(gconv.Strings(res.Label.Array())).ContainsI(consts.AdminMemberLabelGuest) {
	//	data, _ := service.SysConfig().GetConfigByGroup(ctx, &sysin.GetConfigInp{
	//		Group: "points",
	//	})
	//	res.NewMember = true
	//	res.NewMemberPoints = gconv.Float64(data.List["newMemberPoints"])
	//}

	// 订单总数
	res.OrderCount, err = service.SysUserOrder().Count(ctx, memberId)
	if err != nil {
		return
	}

	// 待确认收货订单ID
	confirmOrder := &entity.Order{}
	err = dao.Order.Ctx(ctx).WhereBetween(dao.Order.Columns().MemberCardId, consts.MemberCardId4, consts.MemberCardId5).
		Where(dao.Order.Columns().UserId, memberId).
		Where(dao.Order.Columns().Status, consts.UserOrderStatusExpressed).
		OrderDesc(dao.Order.Columns().CreatedAt).Limit(1).Scan(confirmOrder)
	if err != nil {
	} else {
		res.ConfirmOrderId = confirmOrder.Id
	}

	// 是否显示悬浮按钮
	newCount, err := service.SysUserOrder().ProductNewCount(ctx, memberId)
	if err != nil {
		return
	} else if newCount == 0 {
		res.ShowFloatButton = true
	}

	// 分享收益
	res.ShareProfit = 0 // TODO 临时设置
	if res.RoleId == consts.RoleStore {
		store, err2 := service.SysStore().ViewPhone(ctx, res.Mobile)
		if err2 != nil {
			err = err2
			return
		}
		err2 = gconv.Scan(store, &res.Store)
		if err2 != nil {
			err = err2
			return
		}
		res.Store.Phone = gstr.HideStr(res.Mobile, 40, `*`)
		//} else if consts.IsUserRole(res.RoleId)  { // TODO 临时设置
	} else if garray.NewIntArrayFrom(consts.RoleAllUser2).Contains(gconv.Int(res.RoleId)) {

		res.Distribution.WithdrawableAmount = res.Balance // 可提现

		// TODO 分销中心字段待设置
		res.Distribution.RewardAmount = 0     // 奖励金
		res.Distribution.WithdrawnAmount = 0  // 已提现
		res.Distribution.CommissionIncome = 0 // 佣金收益
		res.Distribution.TeamCount = 0        // 团队人数

		// 获取数据
		err = g.DB().Raw(fmt.Sprintf(`
			SELECT
				-- 累计佣金
				(
					SELECT SUM(num) FROM hg_admin_credits_log 
					WHERE member_id = %d AND credit_group = 'distribution_incr'
				) AS commission_income,
				-- 团队人数
				(
					SELECT COUNT(1) FROM hg_admin_member WHERE (tree LIKE '%s')
				) AS team_count,
				-- 已提现
				(
					SELECT SUM(money) FROM hg_admin_cash WHERE member_id = %d AND status = 4
				) AS withdrawn_amount
			`, memberId, tree.GenLabel(res.Tree, res.Id)+"%", memberId)).Scan(&res.Distribution)
		if err != nil {
			return
		}

		// 总金额
		res.Distribution.TotalAmount = res.Distribution.RewardAmount + res.Distribution.WithdrawableAmount

		// 用户身份
		if consts.IsUserRole(res.RoleId) && res.MemberStatus == consts.AdminMemberMemberStatusMember {
			res.Distribution.Identity = append(res.Distribution.Identity, "会员")
		} else {
			res.Distribution.Identity = append(res.Distribution.Identity, "用户")
		}

		// 代理身份
		if res.RoleId == consts.RoleXiaoke || res.RoleId == consts.RoleService {
			res.Distribution.Identity = append(res.Distribution.Identity, consts.GetRoleName(res.RoleId))
		}
	}

	res.MemberLoginStatModel = stat
	res.Mobile = gstr.HideStr(res.Mobile, 40, `*`)
	res.Email = gstr.HideStr(res.Email, 40, `*`)
	//res.OpenId, _ = service.CommonWechat().GetOpenId(ctx)
	res.DeptType = contexts.GetDeptType(ctx)
	return
}

// MemberLoginStat 用户登录统计
func (s *sAdminMember) MemberLoginStat(ctx context.Context, in *adminin.MemberLoginStatInp) (res *adminin.MemberLoginStatModel, err error) {
	var (
		models *entity.SysLoginLog
		cols   = dao.SysLoginLog.Columns()
	)

	err = dao.SysLoginLog.Ctx(ctx).Fields(cols.LoginAt, cols.LoginIp).
		Where(cols.MemberId, in.MemberId).
		Where(cols.Status, consts.StatusEnabled).
		OrderDesc(cols.Id).
		Scan(&models)

	if err != nil {
		return
	}

	res = new(adminin.MemberLoginStatModel)
	if models == nil {
		return
	}

	res.LastLoginAt = models.LoginAt
	res.LastLoginIp = models.LoginIp
	res.LoginCount, err = dao.SysLoginLog.Ctx(ctx).
		Where(cols.MemberId, in.MemberId).
		Where(cols.Status, consts.StatusEnabled).
		Count()
	return
}

// GetIdByCode 通过邀请码获取用户ID
func (s *sAdminMember) GetIdByCode(ctx context.Context, in *adminin.GetIdByCodeInp) (res *adminin.GetIdByCodeModel, err error) {
	if err = dao.AdminMember.Ctx(ctx).Fields(adminin.GetIdByCodeModel{}).Where(dao.AdminMember.Columns().InviteCode, in.Code).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
	}
	return
}

// GetById 根据ID获取用户
func (s *sAdminMember) GetById(ctx context.Context, in *adminin.GetByIdInp) (res *adminin.GetByIdModel, err error) {
	if err = dao.AdminMember.Ctx(ctx).Fields(adminin.GetByIdModel{}).Where(dao.AdminMember.Columns().Id, in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
	}
	return
}

// GetByMobile 根据手机号获取用户
func (s *sAdminMember) GetByMobile(ctx context.Context, mobile string, roleIds []int) (res *entity.AdminMember, err error) {
	md := dao.AdminMember.Ctx(ctx).Fields(entity.AdminMember{}).
		Where(dao.AdminMember.Columns().Mobile, mobile)
	if len(roleIds) > 0 {
		md = md.WhereIn(dao.AdminMember.Columns().RoleId, roleIds)
	}
	if err = md.Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
	}
	return
}

// Select 获取可选的用户选项
func (s *sAdminMember) Select(ctx context.Context, in *adminin.MemberSelectInp) (res []*adminin.MemberSelectModel, err error) {
	err = dao.AdminMember.Ctx(ctx).Fields("id as value,real_name as label,username,avatar").
		Handler(handler.FilterAuthWithField("id")).
		Scan(&res)
	if err != nil {
		err = gerror.Wrap(err, "获取可选用户选项失败，请稍后重试！")
	}
	return
}

// GetIdsByKeyword 根据关键词查找符合条件的用户ID
func (s *sAdminMember) GetIdsByKeyword(ctx context.Context, ks string) (res []int64, err error) {
	ks = gstr.Trim(ks)
	if len(ks) == 0 {
		return
	}
	array, err := dao.AdminMember.Ctx(ctx).Fields("id").
		Where("`id` = ? or `real_name` = ? or `username` = ? or `mobile` = ?", ks, ks, ks, ks).
		Array()
	if err != nil {
		err = gerror.Wrap(err, "根据关键词获取用户ID失败，请稍后重试！")
	}
	res = gvar.New(array).Int64s()
	return
}

// VerifySuperId 验证是否为超管
func (s *sAdminMember) VerifySuperId(ctx context.Context, verifyId int64) bool {
	s.superAdmin.RLock()
	defer s.superAdmin.RUnlock()

	if s.superAdmin == nil || s.superAdmin.MemberIds == nil {
		g.Log().Error(ctx, "superAdmin is not initialized.")
		return false
	}

	_, ok := s.superAdmin.MemberIds[verifyId]
	return ok
}

// LoadSuperAdmin 加载超管数据
func (s *sAdminMember) LoadSuperAdmin(ctx context.Context) {
	value, err := dao.AdminRole.Ctx(ctx).Fields("id").Where(dao.AdminRole.Columns().Key, consts.SuperRoleKey).Value()
	if err != nil {
		g.Log().Errorf(ctx, "LoadSuperAdmin AdminRole err:%+v", err)
		return
	}

	if value.IsEmpty() || value.IsNil() {
		g.Log().Error(ctx, "the superAdmin role must be configured.")
		return
	}

	array, err := dao.AdminMember.Ctx(ctx).Fields(dao.AdminMember.Columns().Id).Where(dao.AdminMember.Columns().RoleId, value).Array()
	if err != nil {
		g.Log().Errorf(ctx, "LoadSuperAdmin AdminMember err:%+v", err)
		return
	}

	s.superAdmin.Lock()
	defer s.superAdmin.Unlock()

	s.superAdmin.MemberIds = make(map[int64]struct{}, len(array))
	for _, v := range array {
		s.superAdmin.MemberIds[v.Int64()] = struct{}{}
	}
	s.superAdmin.RoleId = value.Int64()
}

// ClusterSyncSuperAdmin 集群同步
func (s *sAdminMember) ClusterSyncSuperAdmin(ctx context.Context, message *gredis.Message) {
	s.LoadSuperAdmin(ctx)
}

// FilterAuthModel 过滤用户操作权限
// 非超管用户只能操作自己的下级角色用户，并且需要满足自身角色的数据权限设置
func (s *sAdminMember) FilterAuthModel(ctx context.Context, memberId int64) *gdb.Model {
	m := dao.AdminMember.Ctx(ctx)
	if s.VerifySuperId(ctx, memberId) {
		return m
	}

	var roleId int64
	if contexts.GetUserId(ctx) == memberId {
		// 当前登录用户直接从上下文中取角色ID
		roleId = contexts.GetRoleId(ctx)
	} else {
		ro, err := dao.AdminMember.Ctx(ctx).Fields("role_id").Where("id", memberId).Value()
		if err != nil {
			g.Log().Panicf(ctx, "failed to get role information, err:%+v", err)
			return nil
		}
		roleId = ro.Int64()
	}

	roleIds, err := service.AdminRole().GetSubRoleIds(ctx, roleId, false)
	if err != nil {
		g.Log().Panicf(ctx, "get the subordinate role permission exception, err:%+v", err)
		return nil
	}
	return m.Where("id <> ?", memberId).WhereIn("role_id", roleIds).Handler(handler.FilterAuthWithField("id"))
}

// 更新用户积分余额
func (this *sAdminMember) UpdateIntegral(ctx context.Context, in *adminin.MemberAddIntegralInp) (err error) {
	_, err = service.AdminCreditsLog().SaveIntegral(ctx, &adminin.CreditsLogSaveIntegralInp{
		MemberId:    in.Id,
		AppId:       in.AppId,
		OrderID:     in.OrderID,
		AddonsName:  in.AddonsName,
		CreditGroup: in.OtherCreditGroup,
		Num:         in.OtherNum,
		Remark:      in.Remark,
	})
	return
}

// Option 获取竞拍活动选项
func (s *sAdminMember) Option(ctx context.Context) (opts []*model.Option, err error) {
	var models []*entity.AdminMember
	if err = s.Model(ctx).Fields(dao.AdminMember.Columns().Id, dao.AdminMember.Columns().RealName).
		OrderDesc(dao.AdminMember.Columns().Id).Scan(&models); err != nil {
		err = gerror.Wrap(err, "获取竞拍活动选项失败！")
		return
	}
	gtime.Now().Weekday()
	opts = make([]*model.Option, len(models))
	for k, v := range models {
		opts[k] = dict.GenHashOption(v.Id, gconv.String(v.RealName))
	}
	return
}

// 开通会员
func (s *sAdminMember) OpenMember(ctx context.Context, in *adminin.OpenMemberInp) (err error) {
	// 查询用户信息
	member, err := service.AdminMember().GetById(ctx, &adminin.GetByIdInp{
		Id: in.MemberId,
	})
	if err != nil {
		return gerror.Wrap(err, "获取用户信息失败")
	}

	// 获取会员卡信息
	memberCard, err := service.ApiOperation().MemberCardDetail(ctx, &apiin.MemberCardDetailInp{
		Id: in.CardId,
	})
	if err != nil {
		return gerror.Wrap(err, "获取会员卡信息失败")
	}

	// 更新用户信息
	memberUpdate := &adminin.MemberUpdateInfoInp{
		ID: member.Id,
	}

	// 根据会员卡类型更新用户信息
	switch memberCard.Type {
	case consts.AdminMemberIdentityMember: // 会员
		memberUpdate.MemberStatus = consts.AdminMemberMemberStatusMember
		memberUpdate.MemberType = memberCard.CardType
		if member.ExpireTime != nil && member.ExpireTime.After(gtime.Now()) { // 用户会员未过期
			memberUpdate.MemberStartTime = member.MemberStartTime
			memberUpdate.ExpireTime = member.ExpireTime.AddDate(0, 0, memberCard.MemberDays+memberCard.ExtraDays)
			memberUpdate.ExchangeCount = member.ExchangeCount + memberCard.ExchangeCount
		} else { // 用户会员已过期
			memberUpdate.MemberStartTime = gtime.Now()
			memberUpdate.ExpireTime = gtime.Now().AddDate(0, 0, memberCard.MemberDays+memberCard.ExtraDays)
			memberUpdate.ExchangeCount = memberCard.ExchangeCount
		}
	case consts.AdminMemberIdentityXiaoke: // 销氪
		memberUpdate.RoleId = consts.RoleXiaoke
	case consts.AdminMemberIdentityService: // 服务商
		memberUpdate.RoleId = consts.RoleService
	}

	// 更新会员信息
	err = service.AdminMember().UpdateInfo(ctx, memberUpdate)
	if err != nil {
		return gerror.Wrap(err, "修改用户信息失败")
	}
	// 订单设置会员过期时间 end_time
	if in.OrderID != 0 && memberCard.Type == consts.AdminMemberIdentityMember {
		_, err = g.DB().Model(dao.Order.Table()).Data("end_time", memberUpdate.ExpireTime).WherePri(in.OrderID).Update()
		if err != nil {
			return gerror.Wrap(err, "更新订单过期时间失败")
		}
	}

	return
}

// GetById 根据ID获取用户身份
func (s *sAdminMember) GetIdentityById(ctx context.Context, id int64) (name string, err error) {
	mb := entity.AdminMember{}
	if err = dao.AdminMember.Ctx(ctx).Fields(entity.AdminMember{}).Where(dao.AdminMember.Columns().Id, id).Scan(&mb); err != nil {
		err = gerror.Wrap(err, "获取用户信息失败，请稍后重试！")
	}
	name = consts.GetRoleName(mb.RoleId)
	if mb.RoleId == consts.RoleUser && mb.MemberStatus == consts.AdminMemberMemberStatusMember {
		name = "会员"
	}
	return
}

// treeList 树状列表
func (s *sAdminMember) treeList(pid int64, nodes []*adminin.AdminMemberT) (list []*adminin.AdminMemberTree) {
	list = make([]*adminin.AdminMemberTree, 0)
	for _, v := range nodes {
		if v.Pid == pid {
			item := new(adminin.AdminMemberTree)
			item.AdminMemberT = *v
			child := s.treeList(v.Id, nodes)
			if len(child) > 0 {
				item.Children = child
			}
			list = append(list, item)
		}
	}
	return
}

// Tree 关系树选项列表
func (s *sAdminMember) Tree(ctx context.Context) (list []*adminin.AdminMemberTree, err error) {
	var models []*adminin.AdminMemberT
	if err = dao.AdminMember.Ctx(ctx).Order("pid asc,id asc").WhereNotIn("id", []int{
		1, 2,
	}).Scan(&models); err != nil {
		err = gerror.Wrap(err, "获取用户关系树选项列表失败！")
		return
	}

	list = s.treeList(1, models)
	return
}

func (s *sAdminMember) TeamList(ctx context.Context, in *apiin.TeamListInp) (list []*apiin.TeamListModel, totalCount int, err error) {

	list = make([]*apiin.TeamListModel, 0)

	mb, err := s.GetById(ctx, &adminin.GetByIdInp{
		Id: contexts.GetUserId(ctx),
	})
	if err != nil {
		return
	}

	cols := dao.AdminMember.Columns()
	mod := s.Model(ctx).
		Fields(apiin.TeamListModel{}).
		Fields(`
			JSON_MERGE(
				CAST(CASE WHEN member_status IN (1, 2) THEN
					JSON_ARRAY(
						CASE
							WHEN member_status = 2 THEN '会员'
							WHEN member_status = 1 THEN '用户'
						END
					)
				ELSE '[]' END AS JSON),
				CAST(CASE WHEN role_id IN (211, 212) THEN
					JSON_ARRAY(
						CASE
							WHEN role_id = 212 THEN '服务商'
							WHEN role_id = 211 THEN '销氪'
						END
					)
				ELSE '[]' END AS JSON)
			) AS identity
		`).
		Fields(fmt.Sprintf(`
			CASE
				WHEN pid = %d THEN '直接推荐'
				ELSE '间接推荐'
			END AS direct_type
		`, mb.Id)).
		WhereLike(cols.Tree, tree.GenLabel(mb.Tree, mb.Id)+"%")

	if in.Search != "" {
		mod = mod.Wheref(cols.Nickname+" like ? OR "+cols.Mobile+" like ?", "%"+in.Search+"%", "%"+in.Search+"%")
	}

	switch in.Type {
	case consts.AdminMemberIdentityUser:
		mod = mod.Where(cols.MemberStatus, consts.AdminMemberMemberStatusUser)
		mod = mod.WhereIn(cols.RoleId, consts.RoleAllUser2)
	case consts.AdminMemberIdentityMember:
		mod = mod.Where(cols.MemberStatus, consts.AdminMemberMemberStatusMember)
		mod = mod.WhereIn(cols.RoleId, consts.RoleAllUser2)
	case consts.AdminMemberIdentityXiaoke:
		mod = mod.Where(cols.RoleId, consts.RoleXiaoke)
	case consts.AdminMemberIdentityService:
		mod = mod.Where(cols.RoleId, consts.RoleService)
	}

	if in.DirectType == 1 {
		mod = mod.Where(cols.Pid, mb.Id)
	} else if in.DirectType == 2 {
		mod = mod.WhereNot(cols.Pid, mb.Id)
	}

	if err = mod.
		Page(in.Page, in.PerPage).OrderDesc(cols.CreatedAt).ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取用户列表失败！")
		return
	}

	return
}

// 根据ID获取用户上级用户集合
func (s *sAdminMember) GetIdentityChain(ctx context.Context, id int64, minIdentity int) (list *[]entity.AdminMember, err error) {

	// 获取用户信息
	mb := &entity.AdminMember{}
	err = dao.AdminMember.Ctx(ctx).WherePri(dao.AdminMember.Columns().Id, id).Scan(&mb)
	if err != nil {
		return
	}

	// 上级ID集合
	idsArray := garray.NewIntArrayFrom(
		gconv.Ints(tree.GetIds(mb.Tree)), // 获取上级ID集合
		false).
		Reverse(). // 倒序（为了获取关系中最近的上级）
		Slice()    // 切片

	idsArray = append(gconv.Ints(mb.Id), idsArray...)

	// 查询上级用户
	array := &[]entity.AdminMember{}
	mod := dao.AdminMember.Ctx(ctx).
		WhereIn(dao.AdminMember.Columns().Id, idsArray)

	mod = mod.Order(fmt.Sprintf("FIELD(%s,%s)", dao.AdminMember.Columns().Id, gstr.Join(gconv.Strings(idsArray), ",")))

	err = mod.Scan(array)
	if gerror.Is(err, sql.ErrNoRows) {
		err = nil
	} else if err != nil {
		return
	}

	// 获取用户上级链条
	if len(*array) > 0 {
		list = &[]entity.AdminMember{}
		identity := minIdentity - 1
		for _, v := range *array {
			vIdentity := consts.GetIdentity(v)
			if vIdentity > identity {
				identity = vIdentity
				*list = append(*list, v)
			}
		}
	}
	return
}
